﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Manager;
using System.Data;
using Model;
using ExtAspNet;
using System.Text;
using Manager.Helper;
using Manager.CustomerHelper;
namespace HealthSystem.sysAdmin
{
    public partial class SchoolMerge : BasePage
    {
        HW_SchoolManager manager = new HW_SchoolManager();
        public override ModuleType Module
        {
            get
            {
                return ModuleType.SchoolManager;
            }
        }
        public static Dictionary<string, List<HW_School>> dic = new Dictionary<string, List<HW_School>>();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                choosebt.OnClientClick = Window2.GetSaveStateReference(OrgCode.ClientID, OrgName.ClientID)
                  + Window2.GetShowReference("~/ChooseOrg.aspx","选择体检机构" );
                Button2.OnClientClick = Window3.GetSaveStateReference(districtname.ClientID, schooldistrictid.ClientID)
                  + Window3.GetShowReference("~/sysadmin/dischoose.aspx","选择区域");
                name.OnClientTriggerClick = Window1.GetSaveStateReference(districtid.ClientID, name.ClientID)
                   + Window1.GetShowReference("~/ChooseDistrict.aspx", "选择区域");
                BindGrid();
                if (!MergeCache.MergeSchool.ContainsKey(User.Identity.Name))
                {
                    MergeCache.MergeSchool.Add(User.Identity.Name,new List<HW_School>());
                }
                else
                {
                    MergeCache.MergeSchool[User.Identity.Name].Clear();
                }
            }
        }
        public void BindGrid()
        {
            int count = 0;
            DataTable list = new DataTable();
            Gird1.IsDatabasePaging = true;
            if (actionbt.Text == "search")
            {
                Search();
            }
            else
            {
                if (!string.IsNullOrEmpty(districtid.Text))
                {
                    list = manager.GetSchoolDetail(Gird1.PageIndex, Gird1.PageSize, out count, districtid.Text);
                    //BindGrid(districtid.Text.Trim());
                }
                else
                {
                    list = manager.GetSchoolDetail(Gird1.PageIndex, Gird1.PageSize, out count, CustomerProfile.DistrictId);
                    //BindGrid(CustomerProfile.DistrictId);
                }
                for (int i = 0; i < list.Rows.Count; i++)
                {
                    list.Rows[i]["permit"] = list.Rows[i]["permit"] is DBNull ? false : list.Rows[i]["permit"];
                }
                Gird1.RecordCount = count;
                this.Gird1.DataSource = list;
                this.Gird1.DataBind();
            }

        }
        private void Search()
        {

            //if (string.IsNullOrEmpty(searchbox.Text))
            //{
            //    ExtAspNet.Alert.Show("请输入查询条件");
            //    return;
            //}
            int count = 0;
            DataTable list = manager.Search(Gird1.PageIndex, Gird1.PageSize, out count, CustomerProfile.DistrictId, searchbox.Text);
            for (int i = 0; i < list.Rows.Count; i++)
            {
                list.Rows[i]["permit"] = list.Rows[i]["permit"] is DBNull ? false : list.Rows[i]["permit"];
            }
            Gird1.RecordCount = count;
            this.Gird1.DataSource = list;
            this.Gird1.DataBind();
            actionbt.Text = "search";
        }
        protected void Search_Clik(object sender, EventArgs e)
        {
            Gird1.PageIndex = 0;
            Search();
        }
        protected void PageIndexChange(object sender, ExtAspNet.GridPageEventArgs e)
        {
            int pageindex = e.NewPageIndex;
            Gird1.PageIndex = pageindex;
            BindGrid();
        }
        protected void selected_Click(object sender, EventArgs e)
        {
            //ExtAspNet.CheckBoxField field1 = (ExtAspNet.CheckBoxField)Gird1.FindColumn("CheckBoxField1");
            int selectedCount = Gird1.SelectedRowIndexArray.Length;
            HW_School school = null;
            HW_School yschool=new HW_School ();
            List<HW_School> list = new List<HW_School>();
            if (selectedCount > 0)
            {
                for (int i = 0; i < selectedCount; i++)
                {
                    int rowIndex = Gird1.SelectedRowIndexArray[i];
                    string schoolcode = Gird1.Rows[rowIndex].DataKeys[0] as string;
                    string name = Gird1.Rows[rowIndex].DataKeys[1] as string;
                    string Statute = Gird1.Rows[rowIndex].DataKeys[2].ToString();
                    //string districtname = Gird1.Rows[rowIndex].DataKeys[2] as string;
                    //string cityname = Gird1.Rows[rowIndex].DataKeys[3] as string;
                  
                    if (Statute != "正常")
                    {
                        Alert.Show(name + "学校已经合并过,或者学校已经停办");
                    }
                    else
                    {
                        school = new HW_School();
                        school.SchoollCode = schoolcode;
                        school.Name = name;
                        var mergelist = ViewState["MergeList"] as List<HW_School>;
                        if (mergelist == null)
                        {
                            var merges = new List<HW_School>();
                            merges.Add(school);
                            ViewState["MergeList"] = merges;
                        }
                        else
                        {
                            if (mergelist.Where(p => p.SchoollCode == schoolcode).Count() == 0)
                            {
                                mergelist.Add(school);
                            }
                            else
                            {
                                Alert.Show(name + "已在合并的列表中");
                            }
                            
                        }
                        //if (MergeCache.MergeSchool[User.Identity.Name].Where(p => p.SchoollCode == schoolcode).Count() == 0)
                        //{
                        //    MergeCache.MergeSchool[User.Identity.Name].Add(school);
                        //}
                        //else
                        //{
                            
                        //}
                    }
                }

                    //list.AddRange(ViewState["dt"] as List<HW_School>);
                grid2.DataSource = ViewState["MergeList"] as List<HW_School>;
                grid2.DataBind();
            }
            else
            {
                Alert.Show("请先选择要合并的学校");
                //sb.Append("<strong>没有选中任何一行！</strong>");
            }


        }
        protected void Row_Command(object sender, ExtAspNet.GridCommandEventArgs e)
        {
            if (e.CommandName == "cacel")
            {
                var list= ViewState["MergeList"] as List<HW_School>;
                if (list != null)
                {
                    list.RemoveAll(p => p.SchoollCode == grid2.Rows[e.RowIndex].Values[0]);
                    grid2.DataSource = list;
                    grid2.DataBind();
                }
            }
        }
        //protected void MergeBt(object sender, EventArgs e)
        //{
        //    if (!dic.ContainsKey(User.Identity.Name))
        //    {
        //        Alert.Show("请先选择需要合并的学校");
        //        return;
        //    }
        //    List<HW_School> list = dic[User.Identity.Name];
        //    System.Text.StringBuilder sb=new System.Text.StringBuilder ();
        //    for (int i = 0; i < list.Count; i++)
        //    {
        //        sb.Append(list[i].SchoollCode.ToString() + ",");
        //    }
        //    ExtAspNet.PageContext.RegisterStartupScript(Window2.GetShowReference("SchoolMerge_Add.aspx?mergeid=" + sb.ToString(), "合并学校"));
        //}
        protected void Window1_Close(object sender,EventArgs e)
        {
            if (!string.IsNullOrEmpty(districtid.Text))
            {
                actionbt.Text = "";
                Gird1.PageIndex = 0;
                BindGrid();
                
            }
        }
        protected void Window2_Close(object sender, EventArgs e)
        {
            BindGrid();
        }
        protected void Save_Click(object sender, EventArgs e)
        {
            string pdistrictId = schooldistrictid.Text;
            if (string.IsNullOrEmpty(schooldistrictid.Text))
            {
                Alert.Show("区域不能为空");
                return;
            }
            //if (string.IsNullOrEmpty(OrgCode.Text))
            //{
            //    Alert.Show("体检机构不能为空");
            //    return;
            //}
            HW_DistrictManager dismanager = new HW_DistrictManager();
            string cityid = dismanager.GetById(pdistrictId).ParentDistrictCode;
            HW_School org = new HW_School();
            //org.SchoollCode = pdistrictId + DateTime.Now.Year.ToString().Substring(1, DateTime.Now.Year.ToString().Length - 1) + DateTime.Now.Minute.ToString().PadLeft(2, '0') + DateTime.Now.Millisecond.ToString().PadLeft(3, '0') + newUserId.ToString().PadLeft(5, '0');
            org.SchoollCode = pdistrictId + DateTime.Now.Year.ToString().Substring(1, DateTime.Now.Year.ToString().Length - 1) + DateTime.Now.Minute.ToString().PadLeft(2, '0') + DateTime.Now.Millisecond.ToString().PadLeft(3, '0') + "11111";
            org.DistrictCode = pdistrictId;
            org.CityId = cityid;
            org.Name = SchoolName.Text;
            org.SchoolType = stype.SelectedText;
            org.OrgCode = OrgCode.Text;
            org.Address = Address.Text;
            org.LinkMan = LinkMan.Text;
            org.OfficePhone = OfficePhone.Text;
            org.MobilePhone = MobilePhone.Text;
            org.Email = Email.Text;
            org.Permit = permitcheck.Checked;
            
            
            StringBuilder merges = new StringBuilder ();
            if (grid2.Rows.Count < 2)
            {
                Alert.Show("至少选择两个学校才能合并");
                return;
            }
            foreach (var g in grid2.Rows)
            {
                merges.Append(g.Values[0]+",");
            }
            string[] mergeArry = merges.ToString().Trim(',').Split(',');
            try
            {
                HW_SchoolMergeLogManager mergerManager = new HW_SchoolMergeLogManager();
                bool permit = permitcheck.Checked;
                mergerManager.SchoolMerge(org, mergeArry, schoolcheck.Checked, permit);
                Alert.Show("学校合并成功！");
                BindGrid();
            }
            catch (Exception ex)
            {
                Alert.Show(ex.Message);
            }
        }
        protected void ShowMergeHistory(object sender, EventArgs e)
        {
            Window2.Width = 800;
            PageContext.RegisterStartupScript(Window2.GetShowReference("MergeHistory.aspx","学校合并历史记录"));
        }
        //protected void Grid1_DoubleClick(object sender, ExtAspNet.GridRowClickEventArgs e)
        //{
        //    string schoolcode = Gird1.Rows[e.RowIndex].DataKeys[0] as string;
        //    string schoolname = Gird1.Rows[e.RowIndex].DataKeys[1] as string;
        //    string url = "~/schoolsignadmin.aspx?schoolcode=" + schoolcode;
        //    PageContext.RegisterStartupScript(Window1.GetShowReference(url, schoolname + "用户"));
        //}

    }
}